﻿using System;
using System.Web;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.Labs.MobilePack.Core.Helpers;
using EPiServer.Security;
using EPiServer.Web;
using InitializationModule = EPiServer.Web.InitializationModule;

namespace EPiServer.Labs.MobilePack.Core
{
    [InitializableModule]
    [ModuleDependency((typeof(InitializationModule)))]
    public class MobileInitializationModule : IInitializableModule
    {
        public void Initialize(InitializationEngine context)
        {
            UrlRewriteModuleBase.HttpRewriteInit += HttpRewriteInit;

            PageBase.PageSetup += this.PageBase_PageSetup;
        }

        public void Preload(string[] parameters)
        {
        }

        public void Uninitialize(InitializationEngine context)
        {
            UrlRewriteModuleBase.HttpRewriteInit -= HttpRewriteInit;
            PageBase.PageSetup -= this.PageBase_PageSetup;
        }

        private static void HttpRewriteInit(object sender, UrlRewriteEventArgs e)
        {
            var urlRewriteModule = (UrlRewriteModule)sender;
            urlRewriteModule.HttpRewritingToInternal += UrlRewriteModuleHttpRewritingToInternal;
        }

        private static void UrlRewriteModuleHttpRewritingToInternal(object sender, UrlRewriteEventArgs e)
        {
            UrlBuilder url = e.Url;

            if (!MobilePackSection.CurrentSection.DisableServerImageResizing && ImageHelper.IsImageRequest(url.Path))
            {
                HttpCookie resolutionCookie = HttpContext.Current.Request.Cookies["resolution"];

                if (resolutionCookie != null)
                {
                    if (IsMobileModeActive() && PrincipalInfo.Current.HasPathAccess(url.Path))
                    {
                        ImageHelper.ResizeImage(url.Path, resolutionCookie.Value);
                    }
                }
            }
        }

        private static bool IsMobileModeActive()
        {
            HttpCookie mobileToggleCookie = HttpContext.Current.Request.Cookies["mobileToggle"];

            return (mobileToggleCookie == null || mobileToggleCookie.Value.Equals("mobile", StringComparison.InvariantCultureIgnoreCase));
        }

        private void PageBase_PageSetup(PageBase sender, PageSetupEventArgs e)
        {
            sender.PreLoad += this.OnPreLoad;
        }

        private void OnPreLoad(object sender, EventArgs e)
        {
            //Check for preview
            var page = sender as EditPage;
            if (page != null)
            {
                if ((page.Request["idkeep"] != null) && string.IsNullOrEmpty(page.Request["InPreview"]))
                {
                    if (!MobilePackSection.CurrentSection.DisablePreview)
                    {
                        string pageTypeName = page.CurrentPage.PageTypeName;
                        string pageTypes = MobilePackSection.CurrentSection.PreviewPageTypes ?? string.Empty;

                        if (pageTypes.Contains(pageTypeName) || pageTypeName.Contains(pageTypes))
                        {
                            page.Response.Redirect(page.ResolveUrl("~/modules/MobilePack.Core/Preview.aspx?OrigUrl=" + page.Server.UrlEncode(page.Request.Url.ToString())), true);
                        }
                    }
                }
            }
        }
    }
}